package cn.fl.project.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.api.ISysRegionApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.comm.facade.framework.dto.SysRegionDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.dto.SysUsrDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.*;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.constant.PrjPrdBscInfoConstant;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IVehicleSrcService;
import cn.fl.project.transform.PrjPrdParamConfigVOTransform;
import cn.fl.project.vo.PrjPrdParamConfigVO;
import com.alibaba.fastjson.JSON;
import cvm.store.facade.cvm.api.IVechileParaConfApiService;
import cvm.store.facade.cvm.dto.VechileParaConfDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import veh.autoinsp.facade.autoinsp.api.IClassDtlRecApiService;
import veh.autoinsp.facade.autoinsp.condition.AutoinspClassDtlRecQC;
import veh.autoinsp.facade.autoinsp.dto.AutoinspClassDtlRecDTO;
import veh.est.facade.estimate.api.IEstResultApiService;
import veh.src.facade.src.src.api.IVehSrcBaseInfApiService;
import veh.src.facade.src.src.api.IVehSrcDetectionApiService;
import veh.src.facade.src.src.api.IVehSrcInfQueryApiService;
import veh.src.facade.src.src.condition.InspectionReportQC;
import veh.src.facade.src.src.condition.VehSrcBaseInfQueryQC;
import veh.src.facade.src.src.dto.VehInspectionReportDTO;
import veh.src.facade.src.src.dto.VehSrcBaseInfDTO;
import veh.src.facade.src.src.dto.VehSrcInfDTO;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class VehicleSrcServiceImpl implements IVehicleSrcService {
    /**
     * 车源查询
     */ private static final Logger logger = LoggerFactory.getLogger(VehicleSrcServiceImpl.class);
    /**
     * 车源查询
     */
    @Autowired
    private IVehSrcInfQueryApiService vehSrcInfQueryApiService;
    /**
     *车源子表信息
     */
    @Autowired
    private IVehSrcBaseInfApiService vehSrcBaseInfApiService;
    /**
     * 数据字典
     */
    @Autowired
    private ISysDictionaryApiService dictionaryApiService;
    @Autowired
    private IVechileParaConfApiService vechileParaConfApiService;
    @Autowired
    private IClassDtlRecApiService classDtlRecApiService;
    @Autowired
    private IEstResultApiService estResultApiService; //估值结果服务
    @Autowired
    private ISysRegionApiService sysRegionApiService;
    @Autowired
    private IPrjBscInfoService prjBscInfoService;
    @Autowired
    private ISysUsrApiService sysUsrApiService;

    @Autowired
    private IVehSrcDetectionApiService vehSrcDetectionApiService;

    public Pager selectListPage(Pager page) {
        //车源列表
        BaseLogUtils.newWebLogger("获取车源列表入参page=" + JSON.toJSONString(page)).info();
        Pager pager = vehSrcDetectionApiService.searchListPage(page);
        BaseLogUtils.newWebLogger("获取车源列表pager=" + JSON.toJSONString(pager)).info();
        List<Long> idList = new ArrayList<Long>();
        if(pager!=null){
            List<VehSrcInfDTO> resultList = (List<VehSrcInfDTO>) pager.getResultList();
            BaseLogUtils.newWebLogger("获取车源列表resultList=" + JSON.toJSONString(resultList)).info();
            if(CollectionUtils.isNotEmpty(resultList)){
                for (VehSrcInfDTO dto : resultList) {
                    idList.add(dto.getId());
                }
                //查询车主名称
                VehSrcBaseInfQueryQC srcBaseInfQueryQC = new VehSrcBaseInfQueryQC();
                srcBaseInfQueryQC.setIds(idList);
                List<VehSrcBaseInfDTO> vehSrcList =  this.vehSrcBaseInfApiService.searchList(srcBaseInfQueryQC);
                BaseLogUtils.newWebLogger("获取车源车主名称vehSrcList=" + JSON.toJSONString(vehSrcList)).info();
                if(CollectionUtils.isNotEmpty(vehSrcList)){
                    for (VehSrcInfDTO dto : resultList) {
                        for (VehSrcBaseInfDTO vehSrcBaseInf : vehSrcList) {
                            if(dto.getId().equals(vehSrcBaseInf.getId())){
                                dto.setOwnerNm(vehSrcBaseInf.getOwnerNm());
                                if (StringUtils.isNotEmpty(dto.getDetectionState())){
                                    dto.setCarState(PrjPrdBscInfoConstant.getCheckCarModeMap.get(dto.getDetectionState().toString()));
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }
        return pager;
    }

    public PrjPrdParamConfigVO getPrdDetail(Long id, String prjTypCd, String buOrgCd) {
        BaseLogUtils.newWebLogger("==获取车源carSourceId=" + id + ",prjTypCd=" + prjTypCd + ",buOrgCd=" + buOrgCd).info();
        PrjPrdParamConfigVO prjPrdParamConfigVO = null;
        try{
            // 查询车型库参配信息主表
            String businessType = PrjBscInfoConstant.getBusinessTypeMap.get(buOrgCd+prjTypCd);
            VehSrcInfDTO vehSrcInf = vehSrcInfQueryApiService.selectVehSrcInfByIdAndBusinessType(id, businessType);
            BaseLogUtils.newWebLogger("getPrdDetail,查询数据车源vehSrcInf:" + JSON.toJSONString(vehSrcInf)).info();
            if (vehSrcInf == null){
                throw new BaseException("车源库中未查到该车源");
            }
            VehSrcBaseInfDTO  vehSrcBaseInfDTO =  vehSrcBaseInfApiService.selectById(id);
            BaseLogUtils.newWebLogger("vehSrcBaseInfDTO:" + JSON.toJSONString(vehSrcBaseInfDTO)).info();
            List<VechileParaConfDTO> vechileParaConfDTOS = null;
            VehInspectionReportDTO vehInspectionReportDTO = new VehInspectionReportDTO();

            Long paraId = vehSrcInf.getParaId();
            //有些信息车源没有取车型库的值
            vechileParaConfDTOS = vechileParaConfApiService.searchByStyleId(paraId);
            BaseLogUtils.newWebLogger("getPrdDetail vechileParaConfDTOS:" + JSON.toJSONString(vechileParaConfDTOS)).info();
            //获取检测报告
            InspectionReportQC inspectionReportQC = new InspectionReportQC();
            inspectionReportQC.setCarId(id);
            inspectionReportQC.setPrjCode(prjTypCd);
            BaseLogUtils.newWebLogger("获取检测报告入参inspectionReportQC:" + JSON.toJSONString(inspectionReportQC)).info();
            DataResultDTO resultDTO = vehSrcInfQueryApiService.getInspectionReport(inspectionReportQC);
            BaseLogUtils.newWebLogger("获取检测报告数据resultDTO:" + JSON.toJSONString(resultDTO)).info();
            if (null!=resultDTO && BaseConstant.IS_YESNO_YES == resultDTO.getSuccess() && null!=resultDTO.getData()){
                vehInspectionReportDTO = (VehInspectionReportDTO) resultDTO.getData();
            }

            //车源库车辆信息
            prjPrdParamConfigVO = PrjPrdParamConfigVOTransform.voVehSrcAdapter(vehSrcInf,vehSrcBaseInfDTO,vechileParaConfDTOS,vehInspectionReportDTO);
            BaseLogUtils.newWebLogger("prjPrdParamConfigVO:" + JSON.toJSONString(prjPrdParamConfigVO)).info();
            //查询市
            SysRegionDTO cyRegion = this.sysRegionApiService.getRegionByRgnCd(vehSrcInf.getCityCode(), CurrentThreadContext.getFlServiceSysCd());
            if(null!=cyRegion){
                prjPrdParamConfigVO.setCityCodeNm(cyRegion.getRgnNm());
                prjPrdParamConfigVO.setParkingLot(cyRegion.getRgnNm());
            }
            double estRetailminprice = 0d;
            double estRetailmaxprice = 0d;
            double estPurminprice = 0d;

            double estPurmaxprice = 0d;
            double purchasingPrice = 0d;
            double evaOfPrice = 0d;
            double vehVal = 0d;
            String insLvl = null;//车辆事故等级
            AutoinspClassDtlRecQC qc = new AutoinspClassDtlRecQC();
            qc.setClassType(0l);
            qc.setPkId(vehSrcInf.getId());
            List<AutoinspClassDtlRecDTO> list =  classDtlRecApiService.searchList(qc);
            BaseLogUtils.newWebLogger("车辆等级结果:"+JSON.toJSONString(list)).info();
            if(CollectionUtils.isNotEmpty(list)){
                insLvl = list.get(0).getClassNm();
            }
            BaseLogUtils.newWebLogger("车辆等级insLvl:"+insLvl).info();
            if (PrjBscInfoConstant.CODE_BU_ORG_CD_ZK.equals(buOrgCd) || PrjBscInfoConstant.CODE_BU_ORG_CD_YC.equals(buOrgCd)){
                if (PrjBscInfoConstant.PRJ_TYP_CD_CDDYWUL.equals(prjTypCd) || PrjBscInfoConstant.PRJ_TYP_CD_OWNJYD.equals(prjTypCd)){
                    if(vehSrcInf.getIsArtificialPrice()==1){
                        //人工零售价
                        if(null!=vehSrcInf.getEvaOfPrice()){
                            vehVal = Double.valueOf(vehSrcInf.getEvaOfPrice());
                        }
                        BaseLogUtils.newWebLogger("获取估值结果1vehVal:" + JSON.toJSONString(vehSrcInf.getEvaOfPrice())).info();
                    }else {
                        //最小零售价
                        if(null!=vehSrcInf.getRetailMinPrice()){
                            vehVal = Double.valueOf(vehSrcInf.getRetailMinPrice());
                        }
                        BaseLogUtils.newWebLogger("获取估值结果2vehVal:" + JSON.toJSONString(vehSrcInf.getRetailMinPrice())).info();
                    }
                }
                if (PrjBscInfoConstant.PRJ_TYP_CD_ESCJYD.equals(prjTypCd)){
                    if(vehSrcInf.getIsArtificialPrice()==1){
                        //人工零售价
                        if(null!=vehSrcInf.getEvaOfPrice()){
                            vehVal = Double.valueOf(vehSrcInf.getEvaOfPrice());
                        }
                        BaseLogUtils.newWebLogger("获取估值结果3vehVal:" + JSON.toJSONString(vehSrcInf.getEvaOfPrice())).info();
                    }else {
                        //最大零售价
                        if(null!=vehSrcInf.getRetailMaxPrice()){
                            vehVal = Double.valueOf(vehSrcInf.getRetailMaxPrice());
                        }
                        BaseLogUtils.newWebLogger("获取估值结果4vehVal:" + JSON.toJSONString(vehSrcInf.getRetailMinPrice())).info();
                    }
                }
            }
            purchasingPrice = vehSrcInf.getPurchasingPrice()==null?0:vehSrcInf.getPurchasingPrice()*10000;
            evaOfPrice = vehSrcInf.getEvaOfPrice()==null?0:Double.valueOf(vehSrcInf.getEvaOfPrice())*10000;
            estPurminprice = DecimalUtils.round(estPurminprice,2);

            estPurmaxprice = DecimalUtils.round(estPurmaxprice,2);

            estRetailmaxprice = DecimalUtils.round(estRetailmaxprice,2);

            estRetailminprice = DecimalUtils.round(estRetailminprice,2);

            purchasingPrice = DecimalUtils.round(purchasingPrice,2);

            evaOfPrice = DecimalUtils.round(evaOfPrice,2);

            BaseLogUtils.newWebLogger("获取估值最终结果11:" + JSON.toJSONString(vehVal)).info();
            vehVal = DecimalUtils.round(vehVal,2);
            BaseLogUtils.newWebLogger("获取估值最终结果22:" + JSON.toJSONString(vehVal)).info();
            BigDecimal vehValBig = new BigDecimal(Double.toString(vehVal));
            vehVal = vehValBig.multiply(new BigDecimal(10000)).doubleValue();
            BaseLogUtils.newWebLogger("获取估值结果vehValBig:" + JSON.toJSONString(vehValBig) + "vehVal:" + JSON.toJSONString(vehVal)).info();

            prjPrdParamConfigVO.setEstPurminpricea(estPurminprice);
            prjPrdParamConfigVO.setEstPurmaxpricea(estPurmaxprice);
            prjPrdParamConfigVO.setEstRetailmaxprice(estRetailmaxprice);
            prjPrdParamConfigVO.setEstRetailminprice(estRetailminprice);
            prjPrdParamConfigVO.setPurchasingPrice(purchasingPrice);
            prjPrdParamConfigVO.setEvaOfPrice(evaOfPrice);
            prjPrdParamConfigVO.setVehVal(vehVal);
            prjPrdParamConfigVO.setClassNm(insLvl);
            prjPrdParamConfigVO.setLicDt(vehSrcInf.getLicDt());
            //验车方式
            if(StringUtils.isNotBlank(prjPrdParamConfigVO.getVehCheckCode())){
              /*  if(prjPrdParamConfigVO.getVehCheckCode().equals("1")){
                    prjPrdParamConfigVO.setVehCheckCodeNm("线上验车");
                }
                if(prjPrdParamConfigVO.getVehCheckCode().equals("2")){
                    prjPrdParamConfigVO.setVehCheckCodeNm("线下验车");
                }*/
                List<KeyValueVO> vehCheckCdList = this.prjBscInfoService.searchVehCheckCdList();
                //验车方式集合
                if(CollectionUtils.isNotEmpty(vehCheckCdList)) {
                    for (KeyValueVO keyValueVO : vehCheckCdList) {
                        if(keyValueVO.getKey().equals(prjPrdParamConfigVO.getVehCheckCode())){
                            prjPrdParamConfigVO.setVehCheckCodeNm(keyValueVO.getValue());
                            break;
                        }
                    }
                }
            }
            // 驱动形式转码
            String drvTypCd = prjPrdParamConfigVO.getDrvTypCd();
            if(StringUtils.isNotBlank(drvTypCd)){
                SysDictionaryDTO cvm0003 = this.dictionaryApiService.getCode("15000", "0000", "CVM0003", drvTypCd);
                prjPrdParamConfigVO.setDrvTypCd(cvm0003.getCodeNm());
            }
            // 用途转码
            String prdNm = prjPrdParamConfigVO.getPrdNm();
            if(StringUtils.isNotBlank(prdNm)){
                SysDictionaryDTO purposeDictionaryDTO = getPurposeDictionaryDTO(prdNm);
                if(purposeDictionaryDTO != null){
                    prjPrdParamConfigVO.setPrdNm(purposeDictionaryDTO.getCodeNm());
                }
            }

            String prdTypCdNm = prjPrdParamConfigVO.getPrdTypCdNm();
            if(StringUtils.isNotBlank(prdTypCdNm)){
                SysDictionaryDTO purposeDictionaryDTO = getPurposeDictionaryDTO(prdTypCdNm);
                if(purposeDictionaryDTO !=null){
                    prjPrdParamConfigVO.setPrdTypCdNm(purposeDictionaryDTO.getCodeNm());
                }
            }
            // 燃料类型转码
            String fuelTypCd = prjPrdParamConfigVO.getFuelTypCd();
            if(StringUtils.isNotBlank(fuelTypCd)){
                SysDictionaryDTO cvm0004 = this.dictionaryApiService.getCode("15000", "0000", "CVM0004", fuelTypCd);
                if(cvm0004!=null){
                    prjPrdParamConfigVO.setFuelTypCd(cvm0004.getCodeNm());
                }
            }
            // 排放标准 CVM0006
            String emiStdCd = prjPrdParamConfigVO.getEmiStdCd();
            if(StringUtils.isNotBlank(emiStdCd)){
                SysDictionaryDTO cvm0006 = this.dictionaryApiService.getCode("15000", "0000", "CVM0006", emiStdCd);
                prjPrdParamConfigVO.setEmiStdCd(cvm0006.getCodeNm());
                prjPrdParamConfigVO.setEmiStd(cvm0006.getCodeNm());
            }
            // 轮胎数量 CVM0006
            String whlNum = prjPrdParamConfigVO.getWhlNum();
            if(StringUtils.isNotBlank(whlNum)){
                SysDictionaryDTO cvm0007 = this.dictionaryApiService.getCode("12000", "00002018", "VEH0054", whlNum);
                prjPrdParamConfigVO.setWhlNum(cvm0007.getCodeNm());
            }
            if(null!=prjPrdParamConfigVO.getDetectionDate()){
                String detectionDateStr  = DateUtils.formatDateToString(prjPrdParamConfigVO.getDetectionDate(),DateUtils.YYYY_MM_DD);
                prjPrdParamConfigVO.setDetectionDateStr(detectionDateStr);
            }
            if(null!=prjPrdParamConfigVO.getLicDt()){
                String licDtStr  = DateUtils.formatDateToString(prjPrdParamConfigVO.getLicDt(),DateUtils.YYYY_MM_DD);
                prjPrdParamConfigVO.setLicDtStr(licDtStr);
            }
            if(StringUtils.isNotBlank(prjPrdParamConfigVO.getRearAxleSpec())){
                if(prjPrdParamConfigVO.getRearAxleSpec().equals("1")){
                    prjPrdParamConfigVO.setRearAxleSpec("半轴桥");//后桥
                }
                if(prjPrdParamConfigVO.getRearAxleSpec().equals("2")){
                    prjPrdParamConfigVO.setRearAxleSpec("轮边减速桥");//后桥
                }
            }
            if(null!=prjPrdParamConfigVO.getReleaseDate()){
                String releaseDateStr  = DateUtils.formatDateToString(prjPrdParamConfigVO.getReleaseDate(),DateUtils.YYYY_MM_DD);
                prjPrdParamConfigVO.setReleaseDateStr(releaseDateStr);
            }
            if(null!=prjPrdParamConfigVO.getSurveyorId()){
                SysUsrDTO sysUsrDTO = this.sysUsrApiService.selectSysUsrById(prjPrdParamConfigVO.getSurveyorId(),"12000","0000");
                if(null!=sysUsrDTO){
                    prjPrdParamConfigVO.setSurveyorNm(sysUsrDTO.getRefRlNm());
                }
            }
            BaseLogUtils.newWebLogger("获取车源库，车源信息:" + JSON.toJSONString(prjPrdParamConfigVO)).info();
            return prjPrdParamConfigVO;
        }catch (BaseException ex) {
            BaseLogUtils.newLogger("车源库，车源信息查询失败,异常bex,id：{}",id)
                    .setThrowable(ex)
                    .error(LogExceptionEnum.COMMON_CODE_0002);
            BaseLogUtils.newLogger("车源库，车源信息查询失败,异常bex,id：{}",id)
                    .setThrowable(ex)
                    .info();
        }catch (Exception ex) {
            BaseLogUtils.newLogger("车源库，车源信息查询失败,异常bex,id：{}",id)
                    .setThrowable(ex)
                    .info();
            BaseLogUtils.newLogger("车源库，车源信息查询失败,异常ex,id：{}",id)
                    .setThrowable(ex)
                    .error(LogExceptionEnum.COMMON_CODE_0002);
        }
        BaseLogUtils.newWebLogger("车源库，车源信息查询结果:" + JSON.toJSONString(prjPrdParamConfigVO) +"id:"+id).info();
        return prjPrdParamConfigVO;
    }

    private SysDictionaryDTO getPurposeDictionaryDTO(String purposeCd) {
        return dictionaryApiService.getCode("15000", "0000", "CVM0001", purposeCd);
    }

    /**
     * 生成估值结果
     * @param styleid
     * @param modelid
     * @param releaseDate
     * @param mil
     * @param cityCode
     * @param slPc
     * @param asTm
     * @return
     */
    private DataResultDTO getDataResult(Long styleid,Long modelid,java.util.Date releaseDate,String mil,String cityCode,Long slPc,java.util.Date asTm,String carType){
        DataResultDTO resultDto = null;
        Long paraId = 0L;//车型id
        Long model_id = 0L;//车系ID
        String release_Dt = "";//出厂时间
        Double mileage = 0.00;//里程
        Long prvCodeId = 0L ;//省ID
        Long cityCodeId = 0L;//市ID
        String as_Tm = "";//年检到期时间
        Double sl_Pc = 0.00;//全款价格（万元）
        Long car_Type = 0L;
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        try{
            if(StringUtils.isNotEmpty(mil)){
                mileage = Double.parseDouble(mil);
                logger.info("里程数:"+mileage);
            }
            if(StringUtils.isNotEmpty(carType)){
                car_Type = Long.parseLong(carType);
                logger.info("用途:"+car_Type);
            }
            if(styleid!=null){
                paraId = styleid;
                logger.info("车型id:"+paraId);
            }
            if(modelid!=null){
                model_id = modelid;
                logger.info("车系id:"+model_id);
            }
            if(releaseDate!=null){
                release_Dt = sdf.format(releaseDate);
                logger.info("出厂时间:"+release_Dt);
            }else{
                release_Dt = sdf.format(new java.util.Date());
            }
            if(StringUtils.isNotEmpty(cityCode)) {
                logger.info("市CODE:"+cityCode);
                SysRegionDTO regionDto = this.sysRegionApiService.getRegionByRgnCd(cityCode, CurrentThreadContext.getFlServiceSysCd());
                if(regionDto!=null){
                    cityCodeId = regionDto.getId();
                    logger.info("市CODE:"+cityCode+"对应的id:"+cityCodeId);
                    if(regionDto.getRgnPid()!=null){//取出父ID
                        if(regionDto.getRgnPid()==160003385){
                            SysRegionDTO region = this.sysRegionApiService.selectById(regionDto.getRgnPid());
                            if(region!=null){
                                prvCodeId = region.getRgnPid();//取出宜春市所属省id
                            }
                        }else if (regionDto.getRgnPid()==0){//直辖市省id传该直辖市市id
                            prvCodeId = regionDto.getId();
                        }else{
                            prvCodeId = regionDto.getRgnPid();
                        }
                        logger.info("省ID:"+prvCodeId);
                    }
                }
            }
            if(asTm != null){
                as_Tm = sdf.format(asTm);
                logger.info("年检到期时间:"+as_Tm);
            }else{
                as_Tm = sdf.format(new java.util.Date());
            }
            if(slPc!=null){
                DecimalFormat df = new DecimalFormat("0.00");
                String slp = df.format((float) slPc / 10000);
                sl_Pc = Double.parseDouble(slp);
                logger.info("全款价格（万元）:"+sl_Pc);
            }
            //默认车辆等级加一个B级对应2
            resultDto = estResultApiService.estCarPrice(paraId, model_id, release_Dt, mileage, prvCodeId, cityCodeId, sl_Pc, as_Tm,Long.valueOf(car_Type),2);
            BaseLogUtils.newWebLogger("获取估值结果.resultDtoDATA:" + com.alibaba.fastjson.JSONObject.toJSONString(resultDto)).info();
        }catch (BaseException ex) {
            BaseLogUtils.newWebLogger("估值价格失败.").setThrowable(ex).error(LogExceptionEnum.API_CODE_0101);
        }catch (Exception ex) {
            BaseLogUtils.newWebLogger("估值价格失败").setThrowable(ex).error(LogExceptionEnum.API_CODE_0101);
        }
        return resultDto;
    }
}
